/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package servointerpreter;

/**
 *
 * @author SchabauerJ
 */
import java.io.*;
import java.net.*;
import java.util.logging.Level;
import java.util.logging.Logger;

class TCPServer {

    static Logger logger = Logger.getLogger(TCPServer.class.getName());
    private static String filename= "pi-blaster";

    public static void start(int port) throws Exception {
        String cmd;
        String capitalizedSentence;
        ServerSocket welcomeSocket = new ServerSocket(port);

        while (true) {
            Socket connectionSocket = welcomeSocket.accept();
            InputStreamReader inputStreamSocket = new InputStreamReader(connectionSocket.getInputStream());
            BufferedReader inFromClient = new BufferedReader(inputStreamSocket);
            DataOutputStream outToClient = new DataOutputStream(connectionSocket.getOutputStream());
            cmd = inFromClient.readLine();
            System.out.println("Received: " + cmd);
            //Übergebe das Telegram an einen Interpreter
            interprete(cmd);

            //capitalizedSentence = cmd.toUpperCase() + '\n';
            outToClient.writeBytes(cmd);
        }
    }

    private static void interprete(String cmd) {
        logger.log(Level.INFO, "Interpreting cmd: " + cmd);
        if (cmd.contains("4")) {
            System.out.println("links\n");
            setServo("1=0.001");
        }
        if (cmd.contains("6")) {
            System.out.println("rechts\n");
            setServo("1=0.002");
        }
    }

    private static void setServo(String cmd) {
        PrintWriter writer = null;
        logger.log(Level.INFO, "Setting Servo: " + cmd);
     
        try {
            logger.log(Level.INFO, "Opening file: " + filename);
     
            writer = new PrintWriter(filename, "UTF-8");
            writer.println(cmd);
            writer.close();
            logger.log(Level.INFO, "Closing file: " + filename);
  
        } catch (UnsupportedEncodingException ex) {
            logger.log(Level.SEVERE, null, ex);
        } catch (FileNotFoundException ex) {
            logger.log(Level.SEVERE, null, ex);
        }
    }
}
